#!/bin/sh

TIMEOUT=25
MOUNTPOINT=/tmp/usb_storage
CAPACITY_FILE=/run/usbhost_capacity

echo "Start testing USB host..."

i=0
while [ $i -lt $TIMEOUT ]; do
    i=$((i + 1))
    echo "Waiting for USB device... $((TIMEOUT - i)) seconds left"
    sleep 1

    # 收集所有可能的 USB 设备（removable=1）
    candidates=""
    for dev in /dev/sd[a-z]; do
        if [ -e "$dev" ]; then
            base=$(basename "$dev")
            if [ -d "/sys/block/$base" ] && [ -f "/sys/block/$base/removable" ]; then
                if [ "$(cat /sys/block/$base/removable)" = "1" ]; then
                    candidates="$candidates $dev"
                fi
            fi
        fi
    done

    # 如果没有候选设备，继续等待
    if [ -z "$candidates" ]; then
        continue
    fi

    echo "Found USB candidates: $candidates"

    # 尝试每个候选设备，直到成功
    for dev in $candidates; do
        base=$(basename "$dev")
        echo "Trying USB device: $dev"

        # 等待分区出现（重要！）
        sleep 2

        # 先尝试分区
        for part in /dev/${base}[0-9]*; do
            if [ -b "$part" ]; then
                echo "Trying to mount partition: $part"
                mkdir -p "$MOUNTPOINT"
                if mount "$part" "$MOUNTPOINT" 2>/dev/null; then
                    echo "Mount successful on $part"
                    umount "$MOUNTPOINT"

                    # 读取容量
                    capacity_kb=$(awk "\$4==\"$base\" {print \$3}" /proc/partitions 2>/dev/null)
                    if [ -n "$capacity_kb" ] && [ "$capacity_kb" -gt 0 ] 2>/dev/null; then
                        echo "$capacity_kb" > "$CAPACITY_FILE"
                        echo "Capacity: ${capacity_kb} KB"
                    else
                        echo "0" > "$CAPACITY_FILE"
                    fi
                    exit 0
                fi
            fi
        done

        # 再尝试整盘（谨慎）
        echo "No partition found on $dev. Trying whole device..."
        mkdir -p "$MOUNTPOINT"
        if mount "$dev" "$MOUNTPOINT" 2>/dev/null; then
            echo "Mounted whole device: $dev"
            umount "$MOUNTPOINT"
            capacity_kb=$(awk "\$4==\"$base\" {print \$3}" /proc/partitions 2>/dev/null)
            if [ -n "$capacity_kb" ] && [ "$capacity_kb" -gt 0 ] 2>/dev/null; then
                echo "$capacity_kb" > "$CAPACITY_FILE"
            else
                echo "0" > "$CAPACITY_FILE"
            fi
            exit 0
        else
            echo "Failed to mount $dev (skipping to next candidate)"
        fi
    done

    # 所有候选都失败，继续等待（可能设备刚插，还没准备好）
    echo "All USB candidates failed. Continuing to wait..."
done

echo "Timed out: no valid USB storage found"
exit 2